const addressModel = require('../model/addressModel.js')
//添加地址
async function add(ctx){
    let id = ctx.user.id
    let address = ctx.request.body.address
    let name = ctx.request.body.name
    let mobile = ctx.request.body.mobile
    let status = ctx.request.body.status
    let regx = /^1[356789]\d{9}$/

    if (!regx.test(mobile)) {
        return ctx.body = { code: 0,msg: '手机号格式有误', data: '' }
    }

    if(!address || address.length < 6 || address.length > 30){
        return ctx.body = {code:0,msg:'地址长度应在6-30位之间',data:''}
    }
    let res = await addressModel.add({id,address,name,mobile,status})
    
    ctx.body = res
}
//删除地址
async function del(ctx){
    let uid = ctx.user.id
    let id = ctx.query.id
    if(typeof id != 'object'){
        id = [id]  
    }
    let res = await addressModel.del({uid,id})
    ctx.body = res
}
//修改地址
async function mod(ctx){
    let id = ctx.request.body.id
    let uid = ctx.user.id
    let newAddress = ctx.request.body.address
    let newMobile =ctx.request.body.tel
    let newName = ctx.request.body.name
    let addrstatus = ctx.request.body.isDefault ? 1 : 0

    let regx = /^1[356789]\d{9}$/
    if (!regx.test(newMobile)) {
        return ctx.body = { code: 0,msg: '手机号格式有误', data: '' }
    }
    
    if(!newAddress || newAddress.length < 6 || newAddress.length > 30){
        return ctx.body = {code:0,msg:'地址长度应在6-30位之间',data:''}
    }

    let res = await addressModel.mod({id,newAddress,newMobile,newName,uid,addrstatus})
    ctx.body = res
}
//获取用户地址
async function list(ctx){
    let id = 1
    let res = await addressModel.list(id)
    ctx.body = res
}   

//获取默认地址
// async function defaultAddr(ctx){
//     let uid = ctx.user.id
//     let res = await addressModel.defaultAddr(uid)
//     ctx.body = res
// }

module.exports ={add,del,mod,list}